package com.psychology.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.psychology.Enum.RoleEnum;
import com.psychology.constant.JwtClaimsConstant;
import com.psychology.constant.MessageConstant;
import com.psychology.dto.UserDTO;
import com.psychology.entity.UserEntity;
import com.psychology.exception.AccountNotFoundException;
import com.psychology.exception.PasswordErrorException;
import com.psychology.mapper.UserMapper;
import com.psychology.properties.JwtProperties;
import com.psychology.service.UserService;
import com.psychology.utile.JwtUtil;
import com.psychology.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper ,UserEntity> implements UserService {

    @Resource
    private JwtProperties jwtProperties;


    /**
     * 用户登录，登录成功生成token并返回
     * @param userDTO
     * @return
     */
    @Override
    public UserVO login(UserDTO userDTO) {

        UserVO user = getByAccountId(userDTO.getAccountId());

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (ObjectUtil.isEmpty(user)) {
            //账号不存在
             throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密处理
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes());
        if (!md5DigestAsHex.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user, userVO);
        userVO.setToken(token);

        return userVO;
    }

    /**
     * 用户注册
     * @param userDTO
     */
    public void registerUser(UserDTO userDTO) {

        if (ObjectUtil.isEmpty(userDTO)) {
            return;
        }
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getAccountId, userDTO.getAccountId());

        UserEntity user = getBaseMapper().selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(user)) {
            throw new AccountNotFoundException(MessageConstant.ALREADY_EXISTS);
        }

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDTO,userEntity);

        //将用户的密码进行加密处理
        userEntity.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));

        getBaseMapper().insert(userEntity);
    }


    /**
     * 查找账号
     * @param accountId
     */
    @Override
    public UserVO getByAccountId(String accountId) {

        if (StrUtil.isEmpty(accountId)) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getAccountId, accountId);

        UserEntity userEntity = getBaseMapper().selectOne(queryWrapper);
        UserVO user = new UserVO();
        BeanUtil.copyProperties(userEntity, user);
        return user;
    }

    /**
     * 重置账号密码
     * @param userDTO
     */
    @Override
    public void recoverPassword(UserDTO userDTO) {
        if (ObjectUtil.isEmpty(userDTO)) {
            return;
        }
        UserEntity userEntity = getBaseMapper().selectById(userDTO.getId());
        BeanUtil.copyProperties(userDTO, userEntity);
        userEntity.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        getBaseMapper().updateById(userEntity);
    }
}